package com.qckj.quartz.service.impl;

import com.qckj.amz.dao.ConfigMarketplaceDao;
import com.qckj.amz.dao.ProductAmzUploadTaskDao;
import com.qckj.amz.dao.ShopAuthDao;
import com.qckj.amz.domain.ProductAmzUploadTask;
import com.qckj.amz.utils.amzApi.AmzHttpUtils;
import com.qckj.amz.utils.amzApi.AmzSpApiUtils;
import com.qckj.amz.utils.constants.AmzConstants;
import com.qckj.amz.utils.constants.QckjConstants;
import com.qckj.common.core.domain.AjaxResult;
import com.qckj.common.tool_qckj.spring.RowMapperUtils;
import com.qckj.common.utils.DateUtils;
import com.qckj.system.service.ISysConfigService;
import io.swagger.client.ApiException;
import io.swagger.client.api.FeedsApi;
import io.swagger.client.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import com.qckj.amz.domain.*;
import com.qckj.amz.utils.enums.EnumMarketplaceIdByCountryCode;
import org.springframework.data.domain.*;
import java.util.*;

/**
 * @author luchuan
 * @version v1.0
 * @date 2022/11/28 0028
 **/

@Service
public class UploadFeedsServiceImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ConfigMarketplaceDao configMarketplaceDao;
    @Autowired
    private ShopAuthDao shopAuthDao;
    @Autowired
    private ProductAmzUploadTaskDao productAmzUploadTaskDao;
    @Autowired
    private ISysConfigService configService;

    public AjaxResult uploadFeeds(){
        //在实现类中获取ProductAmzUploadTask任务数据
        Date date = new Date();
        String sql = "select * from t_product_amz_upload_task t where t.task_status='1' and t.upload_time<= ? ";
        List<ProductAmzUploadTask> productAmzUploadTaskList = jdbcTemplate.query(sql, RowMapperUtils.getRowMapper(ProductAmzUploadTask.class), new Object[]{date});
        if (productAmzUploadTaskList ==null || productAmzUploadTaskList.isEmpty()){
            System.out.println("执行产品上传executeUploadFeeds---共执行数据【0】个");
            return AjaxResult.success();
        }

        //执行上传Feeds任务详细记录
        AjaxResult res = this.executeUploadFeeds(productAmzUploadTaskList);
        // 定时任务执行，无需返回详细结果，已在数据库中记录详细结果与异常
        return AjaxResult.success();
    }

    /**
     * 执行上传Feeds任务详细记录
     * @param productAmzUploadTaskList  待上传的数据
     * @return
     */
    private AjaxResult executeUploadFeeds(List<ProductAmzUploadTask> productAmzUploadTaskList) {

        String reportFrequencyStr = configService.selectConfigByKey("report_frequency");
        if (reportFrequencyStr ==null || reportFrequencyStr.equals("") || !StringUtils.isNumeric(reportFrequencyStr)){
            return AjaxResult.error("获取报告频率为失败，请维护配置表report_frequency参数（报告频率必须为正整数，单位：秒）");
        }
        //遍历上传
        for (ProductAmzUploadTask task: productAmzUploadTaskList) {

            String countryCode = task.getCountryCode();
            String shopCode = task.getShopCode();

            //一、获取站点spapi配置参数
            String marketplaceId = EnumMarketplaceIdByCountryCode.getMarketplaceId(countryCode);

            //同步订单主体信息
            String refreshToken = "";
            String awsRegion =  "";
            String lwaEndpointUri =  "";
            String apiEndpointUri =  "";

            ShopAuth auth = new ShopAuth();
            auth.setShopCode(shopCode);
            auth.setMarketplaceId(marketplaceId);
            auth.setAuthStatus("0");//正常
            Example<ShopAuth> shopAuthExample = Example.of(auth);
            ShopAuth shopAuth = shopAuthDao.findOne(shopAuthExample).orElse(null);
            if (shopAuth==null || shopAuth.getRefreshToken()==null || shopAuth.getRefreshToken().equals("")){
                System.out.println("refreshToken获取为空，请检查店铺授权信息！");
                continue;
            }
            refreshToken = shopAuth.getRefreshToken() == null ? "" : shopAuth.getRefreshToken();

            ConfigMarketplace cmExample = new ConfigMarketplace();
            cmExample.setMarketplaceId(marketplaceId);
            cmExample.setUseStatus("0");
            Example<ConfigMarketplace> configMarketplaceExample = Example.of(cmExample);
            ConfigMarketplace configMarketplace = configMarketplaceDao.findOne(configMarketplaceExample).orElse(null);
            if (configMarketplace!=null){
                awsRegion = configMarketplace.getAwsRegion();
                lwaEndpointUri = configMarketplace.getLwaEndpointUri();
                apiEndpointUri = configMarketplace.getApiEndpointUri();
            }else {
                System.out.println("configMarketplace获取spapi上传配置为空，请检查站点配置信息！");
                continue;
            }

            //通过店铺编号获取已经授权店铺的refreshToken

            if (refreshToken.equals("") || awsRegion.equals("") || lwaEndpointUri.equals("") || apiEndpointUri.equals("") ){
                return AjaxResult.error("");
            }


            /**
             *
             * 二、开始执行spapi上传
             * 1、创建源文档               createFeedDocument
             * 2、封装xml产品信息          FeedXml
             * 3、上传xml产品信息          uploadXmlToAmz
             * 4、创建源                  createFeed
             * 5、获取提要                getFeed
             * 6、获取源文档              getFeedDocument
             */

            Date reportTime = DateUtils.addSeconds(new Date(), Integer.parseInt(reportFrequencyStr));//5分钟后获取上传报告
            //3、封装xml参数准备
            // 4、开始执行上传--程序已在子方法调用中try-catch捕获异常，直接获取返回结果即可

            if (task.getProductFeedStatus().equals(QckjConstants.QC_FEED_STATUS1)){
                AjaxResult res_PRODUCT_FEED = this.uploadFeedsToAmz_PRODUCT_FEED(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri, marketplaceId, AmzConstants.FEED_TYPE_PRODUCT_FEED, task.getProductFeedXml());
                if (res_PRODUCT_FEED.get("code").toString().equals("200")){
                    String feedId = res_PRODUCT_FEED.get("msg").toString();
                    task.setProductFeedId(feedId);
                    task.setProductFeedStatus(QckjConstants.QC_FEED_STATUS2);//上传中
                    task.setReportTime(reportTime);
                }else {
                    String msg = res_PRODUCT_FEED.get("msg").toString();
                    task.setProductFeedResponse(msg);// 上传失败
                    task.setProductFeedStatus(QckjConstants.QC_FEED_STATUS9);//上传失败
                }
            }

            if (task.getPricingFeedStatus().equals(QckjConstants.QC_FEED_STATUS1)){
                AjaxResult res_PRICING_FEED = this.uploadFeedsToAmz_PRICING_FEED(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri, marketplaceId, AmzConstants.FEED_TYPE_PRICING_FEED, task.getPricingFeedXml());
                if (res_PRICING_FEED.get("code").toString().equals("200")){
                    String feedId = res_PRICING_FEED.get("msg").toString();
                    task.setPricingFeedId(feedId);
                    task.setPricingFeedStatus(QckjConstants.QC_FEED_STATUS2);
                    task.setReportTime(reportTime);
                }else {
                    String msg = res_PRICING_FEED.get("msg").toString();
                    task.setPricingFeedResponse(msg);
                    task.setPricingFeedStatus(QckjConstants.QC_FEED_STATUS9);//上传失败
                }
            }

            if (task.getInventoryFeedStatus().equals(QckjConstants.QC_FEED_STATUS1)){
                AjaxResult res_INVENTORY_FEED = this.uploadFeedsToAmz_INVENTORY_FEED(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri, marketplaceId, AmzConstants.FEED_TYPE_INVENTORY_FEED, task.getInventoryFeedXml());
                if (res_INVENTORY_FEED.get("code").toString().equals("200")){
                    String feedId = res_INVENTORY_FEED.get("msg").toString();
                    task.setInventoryFeedId(feedId);
                    task.setInventoryFeedStatus(QckjConstants.QC_FEED_STATUS2);
                    task.setReportTime(reportTime);
                }else {
                    String msg = res_INVENTORY_FEED.get("msg").toString();
                    task.setInventoryFeedResponse(msg);
                    task.setInventoryFeedStatus(QckjConstants.QC_FEED_STATUS9);//上传失败
                }
            }

            if (task.getProductimageFeedStatus().equals(QckjConstants.QC_FEED_STATUS1)){
                AjaxResult res_PRODUCT_IMAGES_FEED = this.uploadFeedsToAmz_PRODUCT_IMAGES_FEED(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri, marketplaceId, AmzConstants.FEED_TYPE_PRODUCT_IMAGES_FEED, task.getProductimageFeedXml());
                if (res_PRODUCT_IMAGES_FEED.get("code").toString().equals("200")){
                    String feedId = res_PRODUCT_IMAGES_FEED.get("msg").toString();
                    task.setProductimageFeedId(feedId);
                    task.setProductimageFeedStatus(QckjConstants.QC_FEED_STATUS2);
                    task.setReportTime(reportTime);
                }else {
                    String msg = res_PRODUCT_IMAGES_FEED.get("msg").toString();
                    task.setProductimageFeedResponse(msg);
                    task.setProductimageFeedStatus(QckjConstants.QC_FEED_STATUS9);//上传失败
                }
            }

            if (task.getRelationshipFeedStatus().equals(QckjConstants.QC_FEED_STATUS1) && task.getRelationshipFeedXml()!=null && !task.getRelationshipFeedXml().equals("")){
                AjaxResult res_RELATIONSHIPS_FEED = this.uploadFeedsToAmz_RELATIONSHIPS_FEED(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri, marketplaceId, AmzConstants.FEED_TYPE_RELATIONSHIPS_FEED, task.getRelationshipFeedXml());
                if (res_RELATIONSHIPS_FEED.get("code").toString().equals("200")){
                    String feedId = res_RELATIONSHIPS_FEED.get("msg").toString();
                    task.setRelationshipFeedId(feedId);
                    task.setRelationshipFeedStatus(QckjConstants.QC_FEED_STATUS2);
                    task.setReportTime(reportTime);
                }else {
                    String msg = res_RELATIONSHIPS_FEED.get("msg").toString();
                    task.setRelationshipFeedResponse(msg);
                    task.setRelationshipFeedStatus(QckjConstants.QC_FEED_STATUS9);//上传失败
                }
            }

            task.setTaskStatus(QckjConstants.QC_TASK_STATUS2);//上传中
            productAmzUploadTaskDao.save(task);
        }

        System.out.println("执行产品上传executeUploadFeeds---共执行数据【"+productAmzUploadTaskList.size()+"】个");
        return AjaxResult.success();
    }



    private AjaxResult uploadFeedsToAmz_PRODUCT_FEED(String awsRegion, String lwaEndpointUri, String refreshToken, String apiEndpointUri, String marketplaceId, String feedType, String feedXml) {
        try {
            //第1步，创建feedsApi对象
            FeedsApi feedsApi = new AmzSpApiUtils(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri).getFeedsApi();

            //第2步，创建createFeedDocument，获取url和feedDocumentId，后面用
            CreateFeedDocumentSpecification body = new CreateFeedDocumentSpecification();
            body.setContentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocumentResponse = feedsApi.createFeedDocument(body);
            System.out.println("FeedsApiTest.createFeedDocumentTest.response==="+feedDocumentResponse);
            String urlAmz = feedDocumentResponse.getUrl();
            String feedDocumentId = feedDocumentResponse.getFeedDocumentId();

            // Upload上传xml
            AmzHttpUtils.uploadXmlToAmz(urlAmz,feedXml);
            // 创建源
            AjaxResult resResponse = createFeed(feedsApi,feedDocumentId,marketplaceId, feedType);
            return resResponse;

        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getResponseBody());
        } catch (InterruptedException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    private AjaxResult uploadFeedsToAmz_PRICING_FEED(String awsRegion, String lwaEndpointUri, String refreshToken, String apiEndpointUri, String marketplaceId, String feedType, String feedXml) {
        try {
            //第1步，创建feedsApi对象
            FeedsApi feedsApi = new AmzSpApiUtils(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri).getFeedsApi();

            //第2步，创建createFeedDocument，获取url和feedDocumentId，后面用
            CreateFeedDocumentSpecification body = new CreateFeedDocumentSpecification();
            body.setContentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocumentResponse = feedsApi.createFeedDocument(body);
            System.out.println("FeedsApiTest.createFeedDocumentTest.response==="+feedDocumentResponse);
            String urlAmz = feedDocumentResponse.getUrl();
            String feedDocumentId = feedDocumentResponse.getFeedDocumentId();

            // Upload上传xml
            AmzHttpUtils.uploadXmlToAmz(urlAmz,feedXml);
            // 创建源
            AjaxResult resResponse = createFeed(feedsApi,feedDocumentId,marketplaceId, feedType);
            return resResponse;
        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getResponseBody());
        } catch (InterruptedException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    private AjaxResult uploadFeedsToAmz_INVENTORY_FEED(String awsRegion, String lwaEndpointUri, String refreshToken, String apiEndpointUri, String marketplaceId, String feedType, String feedXml) {
        try {
            //第1步，创建feedsApi对象
            FeedsApi feedsApi = new AmzSpApiUtils(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri).getFeedsApi();

            //第2步，创建createFeedDocument，获取url和feedDocumentId，后面用
            CreateFeedDocumentSpecification body = new CreateFeedDocumentSpecification();
            body.setContentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocumentResponse = feedsApi.createFeedDocument(body);
            System.out.println("FeedsApiTest.createFeedDocumentTest.response==="+feedDocumentResponse);
            String urlAmz = feedDocumentResponse.getUrl();
            String feedDocumentId = feedDocumentResponse.getFeedDocumentId();

            // Upload上传xml
            AmzHttpUtils.uploadXmlToAmz(urlAmz,feedXml);
            // 创建源
            AjaxResult resResponse = createFeed(feedsApi,feedDocumentId,marketplaceId, feedType);
            return resResponse;
        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getResponseBody());
        } catch (InterruptedException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    private AjaxResult uploadFeedsToAmz_PRODUCT_IMAGES_FEED(String awsRegion, String lwaEndpointUri, String refreshToken, String apiEndpointUri, String marketplaceId, String feedType, String feedXml) {
        try {
            //第1步，创建feedsApi对象
            FeedsApi feedsApi = new AmzSpApiUtils(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri).getFeedsApi();

            //第2步，创建createFeedDocument，获取url和feedDocumentId，后面用
            CreateFeedDocumentSpecification body = new CreateFeedDocumentSpecification();
            body.setContentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocumentResponse = feedsApi.createFeedDocument(body);
            System.out.println("FeedsApiTest.createFeedDocumentTest.response==="+feedDocumentResponse);
            String urlAmz = feedDocumentResponse.getUrl();
            String feedDocumentId = feedDocumentResponse.getFeedDocumentId();

            AmzHttpUtils.uploadXmlToAmz(urlAmz,feedXml);
            // 创建源
            AjaxResult resResponse = createFeed(feedsApi,feedDocumentId,marketplaceId, feedType);
            return resResponse;
        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getResponseBody());
        } catch (InterruptedException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    private AjaxResult uploadFeedsToAmz_RELATIONSHIPS_FEED(String awsRegion, String lwaEndpointUri, String refreshToken, String apiEndpointUri, String marketplaceId, String feedType, String feedXml) {
        try {
            //第1步，创建feedsApi对象
            FeedsApi feedsApi = new AmzSpApiUtils(awsRegion, lwaEndpointUri, refreshToken, apiEndpointUri).getFeedsApi();

            //第2步，创建createFeedDocument，获取url和feedDocumentId，后面用
            CreateFeedDocumentSpecification body = new CreateFeedDocumentSpecification();
            body.setContentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocumentResponse = feedsApi.createFeedDocument(body);
            System.out.println("FeedsApiTest.createFeedDocumentTest.response==="+feedDocumentResponse);
            String urlAmz = feedDocumentResponse.getUrl();
            String feedDocumentId = feedDocumentResponse.getFeedDocumentId();

            // Upload上传xml
            AmzHttpUtils.uploadXmlToAmz(urlAmz,feedXml);
            // 创建源
            AjaxResult resResponse = createFeed(feedsApi, feedDocumentId, marketplaceId, feedType);
            return resResponse;
        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getResponseBody());
        } catch (InterruptedException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 第5步
     * 创建源
     *
     * @param feedsApi
     * @param feedDocumentId
     * @param marketplaceId
     * @param feedType
     * @throws ApiException
     */
    private AjaxResult createFeed(FeedsApi feedsApi, String feedDocumentId, String marketplaceId, String feedType) throws ApiException, InterruptedException {
        CreateFeedSpecification body = new CreateFeedSpecification();
        List<String> Ids = new ArrayList<>();
        Ids.add(marketplaceId);
        body.setMarketplaceIds(Ids);
        body.setFeedType(feedType);
        body.setInputFeedDocumentId(feedDocumentId);//第一部获取的feedDocumentId

        Thread.sleep(2000);
        CreateFeedResponse feedResponse = feedsApi.createFeed(body);
        System.out.println(feedResponse.getFeedId());//保存feedID 后面过几分钟根据它获取上传报告

        return AjaxResult.success(feedResponse.getFeedId());
    }


}
